import { defineStore } from 'pinia'

import cookie from '@/utils/cookie'
import { getUserInfo, getMallConfig } from '@/api/user'
import { useRouter } from "@/hooks/useRouter";
import { getIntegralName } from "@/api/member";
import { loginLogoIcon } from "@/utils/images";
import store from "@/store";

const {push} = useRouter()

export const useMainStore = defineStore('main', {
    state: () => ({
        user: null,
        areaList: [],
        selectAddress: null,
        moreLoading: true,
        cartId: null,
        integralName: '积分',
        logoSrc: loginLogoIcon
    }),
    getters: {},
    actions: {
        setAccessToken(user) {
            cookie.set('accessToken', user)
            return getUserInfo()
        },
        setSelectAddress(id) {
            this.selectAddress = this.address.filter(item => item.id == id)[0]
        },
        async getUserInfo() {
            let res = await getUserInfo()
            this.user = res
            return res
        },
        async getMallLogo() {
            let res = await getMallConfig()
            this.logoSrc = res.appLogo
        },
        init() {
            let accessToken = cookie.get('accessToken')
            if (accessToken) {
                return getUserInfo()
            }
            return null
        },
        logout() {
            this.user = null
            this.address = []
            this.areaList = []
            this.selectAddress = null
            cookie.remove('accessToken')
            push({url: '/pages/login/guid'}, {type: "redirectTo"})
        },
        async doGetIntegralName() {
            this.integralName = await getIntegralName()
        }
    },
})

export const useMainStoreWithOut = () => useMainStore(store)
